<?php

namespace App\Service\OpenShop\Merchant;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Remote\Rms\RmsAreaRemote;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Organization\WarZoneService;
use App\Service\SiteLocation\SiteLocationLogicService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;

class SiteLocationPushMsgService
{


    const PROVINCE_CODE_FUJIAN   = '350000'; // 福建省code
    const PROVINCE_CODE_ZHEJIANG = '330000'; // 浙江省code


    /**
     *  获取推送的卡片信息
     * @param string $orderNo
     * @param object $siteLocationModel
     * @param int $merchantConfirmTime
     * @param int $shopCode
     * @throws GuzzleException
     * @throws \Exception
     */
    public static function getCardMsg(
        string $orderNo,
        object $siteLocationModel,
        int $merchantConfirmTime,
        int $shopCode
    )
    {
        // 通过省区获得分公司
        $organizationModel = OpenShopOrganizationRegionMappingModel::query()
                                                                   ->where('provinceCode',
                                                                       $siteLocationModel->provinceCode)
                                                                   ->with(['organizationManageRel'])
                                                                   ->first();

        if (!empty($organizationModel)) {

            // 获取菜单等级
            $cityGradeInfo = RmsAreaRemote::getCityGrade($siteLocationModel->cityCode)["cityInfo"];

            // 分公司名称
            $branchCompany = ((string)optional($organizationModel->organizationManageRel)->name) ?: '-';

            // 省市区
//            $provinceName = (string)$organizationModel->provinceName ?: '-';
//            $provinceName = (string)$organizationModel->provinceName ?: '-';
            $provinceName = (string)$organizationModel->provinceName ?: '-';

            // 是否艾特所有人
            $isEtAll      = (int)ConfigModel::query()->where('module', 'siteLocation')->where('name', 'isEtAll')
                                            ->value('value');
            $isEtAllStr   = $isEtAll ? "<at id=all></at>" : '';

            // 信息来源
            $messageFrom = SiteLocationEnum::MESSAGE_FROM_TYPE_TEXT[$siteLocationModel->messageFrom] ?? '';

            // 城市地址
            $cityArea = $siteLocationModel->cityArea;

            // 城市菜单等级
            $cityMenuLevel = $cityGradeInfo['menuLevel'] ?? '-';

            // 城市等级
            $cityTypeText = SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[$siteLocationModel->cityType] ?? '-';

            // 签约地址
            $address = $siteLocationModel->address;

            // 获取主流程信息
            $mainProcessInfo = OpenShopMainProcessModel::query()->where('orderNo',$orderNo)->first();

            // 是否迁址
            $isRelocate = false;
            if (!empty($mainProcessInfo) && $mainProcessInfo->childLocationOrder == MainProcessEnum::CHILD_ORDER_1){
                $isRelocate = true;
            }

            $signOrderCreatedAt = OpenShopSignOrderModel::query()
                ->where('orderNo', $orderNo)
                ->value('createdAt');

            // 确址时间 $merchantConfirmTime
            $merchantConfirmDate = date("Y-m-d H:i:s", $merchantConfirmTime);

            $userContractInfo = OpenShopUserContractModel::query()->where("orderNo", $orderNo)->first();
            $signDate = '-';
            $spaceDay = '-';
            if (!empty($userContractInfo->signTime)){
                // 签约时间： 合同签约时间
                $signDate = date("Y-m-d H:i:s", $userContractInfo->signTime);

                // 间隔时长
                if ($isRelocate) {
                    $spaceDay = ceil(($merchantConfirmTime - $signOrderCreatedAt->timestamp) / 86400);
                } else {
                    $spaceDay = ceil(($merchantConfirmTime - $userContractInfo->signTime) / 86400);
                }
            }

            // 开发经理信息
            $developUserInfo   = KmsUser::query()->where('rmsUserId', $siteLocationModel->developConsultantId)->first();
            $developUserOpenId = $developUserInfo->openId;
            $developUserName   = $siteLocationModel->developConsultantName;

            // 用户信息处理
            $rmsShopInfo = (new RmsShopApi())->getShopByCode($shopCode);
            $shopName    = $rmsShopInfo['data']['name'];
            $shopMobile  = $rmsShopInfo['data']['shopMobile'];
            $firstChar        = mb_substr($shopName, 0, 1, 'UTF-8'); // 获取第一个字符
            $maskedNumber     = substr($shopMobile, 0, 3) . str_repeat("*", 4) . substr($shopMobile, -4);
            $shopNameAndPhone = $firstChar . "** (" . $maskedNumber . ")";


            // 针对品牌设计卡片调整
            $brandDesignCard = [
                'config'   => [
                    'wide_screen_mode' => true,
                ],
                "header"   => [
                    'template' => "purple",
                    "title"    => [
                        "content" => "【{$shopCode}】有新的「{$cityMenuLevel}级菜单」门店落位，请注意"
                    ]
                ],
                'elements' => [
                    [
                        "tag"     => "markdown",
                        "content" => ("门店编号：" . $shopCode ?? "-") . " (" . $cityMenuLevel . "级菜单)",
                    ],
                    [
                        "tag"     => "markdown",
                        "content" => "落位区域：" . $cityArea . "(" . $cityTypeText . ")",
                    ]
                ]
            ];



            // 推送卡片消息:
            $cardContent =  [
                'config'   => [
                    'wide_screen_mode' => true,
                ],
                "header"   => [
                    'template' => "purple",
                    "title"    => [
                        "content" => "🎉🎉 🎉 恭喜" . $branchCompany . " @" . $developUserName . "开发经理「" . $messageFrom . "」落位" . $cityArea . "！🔥🔥🔥"
                    ]
                ],
                'elements' => [
                    [
                        "tag"     => "markdown",
                        "content" => "客户信息：" . $shopNameAndPhone,
                    ],
                    [
                        "tag"     => "markdown",
                        "content" => ("门店编号：" . $shopCode ?? "-") . " (" . $cityMenuLevel . "级菜单)",
                    ],
                    [
                        "tag"     => "markdown",
                        "content" => "落位区域：" . $cityArea . "(" . $cityTypeText . ")",
                    ],
                    [
                        "tag"     => "markdown",
                        "content" => "落位地址：" . $address,
                    ],
                ],
            ];

            $positionRate = 0;

            if ($spaceDay != '-') {
                try {
                    $rate = DB::select("SELECT (SELECT COUNT(*) FROM open_shop_statistics WHERE CAST(addition AS UNSIGNED) <= {$spaceDay}) / COUNT(*) * 100 AS percentile FROM open_shop_statistics");
                    $positionRate = round(100 - $rate[0]->percentile, 2);
                } catch (\Exception $exception) {}
            }

            // 迁址店不显示 确址时间 、签约时间、落位时长
            // if (!$isRelocate){
            //     $cardContent['elements'][] =  [
            //         "tag"     => "markdown",
            //         "content" => "确址时间：" . $merchantConfirmDate,
            //     ];
            //     $cardContent['elements'][] =  [
            //         "tag"     => "markdown",
            //         "content" => "签约时间：" . $signDate,
            //     ];
            //     $cardContent['elements'][] =[
            //         "tag"     => "markdown",
            //         "content" => $positionRate ? "落位时长：**" . $spaceDay . "天** (击败全国{$positionRate}%的门店)" : "落位时长：**" . $spaceDay . "天**",
            //     ];
            // }

            $cardContent['elements'][] =  [
                "tag"     => "markdown",
                "content" => "确址时间：" . $merchantConfirmDate,
            ];
            $cardContent['elements'][] =  [
                "tag"     => "markdown",
                "content" => "签约时间：" . $signDate,
            ];

            if ($isRelocate){
                $cardContent['elements'][] =[
                    "tag"     => "markdown",
                    "content" => "迁址申请：" . $signOrderCreatedAt->toDateTimeString(),
                ];
            }

            $cardContent['elements'][] =[
                "tag"     => "markdown",
                "content" => $positionRate ? "落位时长：**" . $spaceDay . "天** (击败全国{$positionRate}%的门店)" : "落位时长：**" . $spaceDay . "天**",
            ];

            // 追加尾部
            $cardContent['elements'][] =
                [
                    "tag"     => "markdown",
                    "content" => "开发经理：<at id=" . $developUserOpenId . "></at>",
                ];
            $cardContent['elements'][] =         [
                "tag"     => "div",
                'text'=>[
                    "tag"=>"lark_md",
                    "content" => "👏 👏 👏 " . $isEtAllStr . " 热烈祝贺**<font color='red'> " . $branchCompany . "</font>** 再下一店！💪 💪 💪 每一个客户的成功都离不开各团队的紧密配合！",
                ],

            ];

            // 群1 - 夸父选址
            BuildFs::newRobot(SendFs::ROBOT_INTENDED_SITE_SELECTION_CONFIRM_KF, BuildFs::MSG_TYPE_CARD)
                   ->setCardContent($cardContent)
                   ->send();

            // 群2 - 品牌设计
            BuildFs::newRobot(SendFs::ROBOT_INTENDED_SITE_SELECTION_CONFIRM_DESIGN, BuildFs::MSG_TYPE_CARD)
                   ->setCardContent($brandDesignCard)
                   ->send();

            // 开发群 只推送 上海-310000 的
            if ($siteLocationModel->provinceCode == 310000) {
                BuildFs::newRobot(SendFs::ROBOT_INTENDED_SITE_SELECTION_CONFIRM_DMG, BuildFs::MSG_TYPE_CARD)
                    ->setCardContent($cardContent)
                    ->send();
            }

            try {
                $regionDivideModel =  WarZoneService::getWarZoneInfoByProvinceCode($siteLocationModel->provinceCode, ['regionId']);
                // 战区推送
                $regionDivideId = $regionDivideModel ? $regionDivideModel->regionId : 0;

                if ($regionDivideId && config('app.env') != 'pre') {
                    $robot = SiteLocationLogicService::getRobotByRegionManageId($regionDivideId);
                    foreach ($robot as $robotItem) {
                        BuildFs::newRobot(0, BuildFs::MSG_TYPE_CARD)
                            ->setCardContent($cardContent)
                            ->setRobotConfig($robotItem['url'], $robotItem['token'])
                            ->send();
                    }
                }
            } catch (\Exception $exception) {}

            // 浙江，福建 单独推送
            if (in_array($siteLocationModel->provinceCode, [
                SiteLocationPushMsgService::PROVINCE_CODE_FUJIAN,
                SiteLocationPushMsgService::PROVINCE_CODE_ZHEJIANG
            ])) {

                // 获取跳转地址
                $jumpUrl = BaseService::getSiteAppletUrl($orderNo);
                // 增加查看按钮
                $cardContent['elements'][] = [
                    'tag' => 'hr'
                ];
                $cardContent['elements'][] = [
                    'tag'     => 'action',
                    'actions' => [
                        [
                            'tag'       => 'button',
                            'type'      => 'primary',
                            'text'      => [
                                'tag'     => 'plain_text',
                                'content' => '点击查看',
                            ],
                            'multi_url' => [
                                'url'         => $jumpUrl,
                                'android_url' => $jumpUrl,
                                'ios_url'     => $jumpUrl,
                                'pc_url'      => $jumpUrl,
                            ],
                        ],
                    ]
                ];

                // 群3
                BuildFs::newRobot(SendFs::ROBOT_INTENDED_SITE_SELECTION_CONFIRM_ZF, BuildFs::MSG_TYPE_CARD)
                       ->setCardContent($cardContent)
                       ->send();
            }

        }

    }


}
